
import java.util.concurrent.CyclicBarrier;

import com.jcraft.jsch.Channel;
import com.jcraft.jsch.JSch;
import com.jcraft.jsch.Session;

public class SSHTester implements Runnable {

	
	ConnectionStatus sshStatus = new ConnectionStatus();
	ResultsTable sharedTable = new ResultsTable();
	private int numTests;
	static CyclicBarrier barrier;
	
	private static final String SSH_KEY = "ssh";
	
	
	public SSHTester(ResultsTable table, CyclicBarrier b, int n) {
		sharedTable = table;
		numTests = n;
		barrier = b;
	}
	
	public ConnectionStatus runTests (int n) {
		
		for (int i = 0; i < n; i++){
			if (isConnected()) {
				this.sshStatus.addPassedAttempt();
			} else {
				this.sshStatus.addFailedAttempt();
			}
		}
		
		return this.sshStatus;
		
	}
	
	private boolean isConnected(){
		
		try {
			
			JSch jsch = new JSch();
			String user = "mifc";
			String host = "sdf.org";
			String passwd = "mifc123";
			int port = 22;
			
			Session session = jsch.getSession(user, host, port);
			session.setPassword(passwd);
			session.setConfig("StrictHostKeyChecking", "no");
			session.connect(10000);
			
			Channel channel = session.openChannel("shell");
			channel.connect(3000);
			
			channel.disconnect();
			session.disconnect();
			
			return true;
			
		} catch (Exception e) {
			return false;
		}
		
	}
	
	
	@Override
	public void run() {
		System.out.println("Running ssh tester");
		sshStatus = runTests(numTests);
		sharedTable.addResult(SSH_KEY, sshStatus);
	
		try {
			barrier.await();
		} catch (Exception e) {
			e.printStackTrace();
		}
		
	}
	
	
	
	

}
